﻿using NewsSystem.ClientModels;
using NewsSystem.Contracts;
using NewsSystem.Models;
using System;
using System.Net.Http;
using System.Web.Http;

namespace NewsSystem.WebApi.Controllers
{
    public class VotesController : BaseController
    {
        public VotesController(INewsUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        // POST api/votes
        public HttpResponseMessage Post([FromBody]VoteModel voteModel, string sessionId)
        {
            var responseMsg = this.PerformOperation(() =>
            {
                var currentAuthor = this.Uow.User.GetBySessionId(sessionId);
                if (currentAuthor == null)
                {
                    throw new ArgumentException("Invalid session id.");
                }

                var article = this.Uow.Article.Get(voteModel.ArticleId);
                var vote = new Vote
                {
                    Article = article,
                    Author = currentAuthor,
                    Value = voteModel.Value,
                };

                this.Uow.Vote.Add(vote);
                this.Uow.Commit();
            });

            return responseMsg;
        }

        // PUT api/votes/5
        public HttpResponseMessage Put(int id, [FromBody]VoteModel voteModel, string sessionId)
        {
            var responseMsg = this.PerformOperation(() =>
            {
                var currentAuthor = this.Uow.User.GetBySessionId(sessionId);
                if (currentAuthor == null)
                {
                    throw new ArgumentException("Invalid session id.");
                }

                var vote = this.Uow.Vote.Get(voteModel.Id);
                if (vote != null && vote.Author.Id == currentAuthor.Id)
                {
                    vote.Value = voteModel.Value;
                    this.Uow.Commit();
                }
                else
                {
                    throw new ArgumentException("Wrong user or voteId");
                }
            });

            return responseMsg;
        }
    }
}
